from fastapi import Request


def get_real_ip(request: Request) -> str:
    """安全获取真实客户端IP（处理代理情况）

    nginx 配置

    server {
        location / {
            # 必须配置以下header才能正确传递IP
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://fastapi_backend;
            }
        }

    """
    # 优先从X-Forwarded-For获取（需代理配置）
    forwarded = request.headers.get("X-Forwarded-For")
    if forwarded:
        # 取第一个IP（可能是客户端原始IP）
        client_ip = forwarded.split(",")[0].strip()
        return client_ip

    # 备用从X-Real-IP获取
    real_ip = request.headers.get("X-Real-IP")
    if real_ip:
        return real_ip

    # 回退到连接IP
    return request.client.host or "127.0.0.1"
